<template>
  <div class="page">
    <!-- 点位选择 -->
    <div class="point-list">
      <label v-for="point in allPoints" :key="point.id">
        <input
          v-model="selectedPoints"
          type="checkbox"
          :value="point"
          @change="handlePointChange"
        />
        {{ point.name }}
      </label>
    </div>

    <!-- 图表区 -->
    <div class="charts">
      <div v-for="chart in charts" :key="chart.id" class="chart-item">
        <div class="chart-header">
          <span>{{ chart.name }}</span>
          <input
            v-model="chart.startTime"
            type="datetime-local"
            @change="updateChartData(chart)"
          />
          <input
            v-model="chart.endTime"
            type="datetime-local"
            @change="updateChartData(chart)"
          />
          <button @click="removeChart(chart.id)">删除</button>
        </div>

        <!-- 图表容器，用ref方式绑定 -->
        <div
          :ref="(el) => chartRefs.set(chart.id, el as HTMLElement)"
          class="chart-box"
        ></div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import * as echarts from "echarts";

// 模拟点位数据
const allPoints = ref([
  { id: "p1", name: "温度点位" },
  { id: "p2", name: "压力点位" },
  { id: "p3", name: "流量点位" },
]);

// 当前选中的点位
const selectedPoints = ref<any[]>([]);

// 图表数据（每个点位一个chart对象）
const charts = reactive<any[]>([]);

// 保存每个图表的 DOM 引用
const chartRefs = new Map<string, HTMLElement>();

// 保存每个 ECharts 实例
const chartInstances = new Map<string, echarts.ECharts>();

// 点位选择变化时
const handlePointChange = async () => {
  const selectedIds = selectedPoints.value.map((p) => p.id);
  const chartIds = charts.map((c) => c.id);

  // 添加新图表
  selectedPoints.value.forEach(async (p) => {
    if (!chartIds.includes(p.id)) {
      charts.push({
        id: p.id,
        name: p.name,
        startTime: "",
        endTime: "",
      });
      await nextTick();
      initChart(p.id);
    }
  });

  // 删除取消选中的
  charts.forEach((c) => {
    if (!selectedIds.includes(c.id)) {
      removeChart(c.id);
    }
  });
};

// 初始化图表
const initChart = (id: string) => {
  const el = chartRefs.get(id);
  if (!el) return;

  const instance = echarts.init(el);
  chartInstances.set(id, instance);

  instance.setOption({
    title: { text: charts.find((c) => c.id === id)?.name || "" },
    tooltip: { trigger: "axis" },
    xAxis: { type: "category", data: [] },
    yAxis: { type: "value" },
    series: [{ type: "line", data: [] }],
  });

  updateChartData(charts.find((c) => c.id === id));
};

// 更新图表数据
const updateChartData = (chart: any) => {
  const instance = chartInstances.get(chart.id);
  if (!instance) return;

  // 模拟数据
  const times = Array.from({ length: 10 }, (_, i) => `10:${i}0`);
  const values = times.map(() => Math.random() * 100);

  instance.setOption({
    xAxis: { data: times },
    series: [{ data: values }],
  });
};

// 删除图表
const removeChart = (id: string) => {
  // 释放ECharts实例
  const instance = chartInstances.get(id);
  if (instance) {
    instance.dispose();
    chartInstances.delete(id);
  }

  // 删除chart对象
  const index = charts.findIndex((c) => c.id === id);
  if (index !== -1) charts.splice(index, 1);

  // 删除ref引用
  chartRefs.delete(id);
  selectedPoints.value = selectedPoints.value.filter((p) => p.id !== id);
};

// 页面卸载时释放所有实例
onBeforeUnmount(() => {
  chartInstances.forEach((inst) => inst.dispose());
  chartInstances.clear();
});
</script>

<style scoped>
.page {
  padding: 16px;
}
.point-list {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
}
.charts {
  display: flex;
  flex-direction: column;
  gap: 24px;
}
.chart-item {
  border: 1px solid #ddd;
  padding: 10px;
  border-radius: 8px;
}
.chart-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}
.chart-box {
  width: 100%;
  height: 300px;
}
</style>
